package cn.wolfcode.exception;

import cn.wolfcode.domain.JsonResult;
import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@ControllerAdvice
public class HandlerControllerException {

    @ExceptionHandler(RuntimeException.class)
    public String handlerException(RuntimeException e, HttpServletResponse resp , HandlerMethod method){
        e.printStackTrace();
        if(method.hasMethodAnnotation(ResponseBody.class)){
            String errorMsg = "您没有权限操作";
            resp.setContentType("application/json;charset=utf-8");
            JsonResult jsonResult = new JsonResult(false ,errorMsg);
            try {
                resp.getWriter().print(JSON.toJSONString(jsonResult));
            } catch(IOException e1) {
                e1.printStackTrace();
            }
            return null ;
        }else {
            return "common/nopermission";
        }
    }

    @ExceptionHandler(UnauthorizedException.class)
    public String handlerException(UnauthorizedException e, HttpServletResponse resp , HandlerMethod method){
        e.printStackTrace();
        if(method.hasMethodAnnotation(ResponseBody.class)){
            resp.setContentType("application/json;charset=utf-8");
            JsonResult jsonResult = new JsonResult(false ,"亲, 您没有权限访问");
            try {
                resp.getWriter().print(JSON.toJSONString(jsonResult));
            } catch(IOException e1) {
                e1.printStackTrace();
            }
            return null ;
        }else {
            return "common/nopermission";
        }
    }
}
